package com.ruoyi.web.controller.market.extend;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.db.domain.ChannelInfo;
import com.ruoyi.db.domain.CountInfo;
import com.ruoyi.db.domain.ProductPush;
import com.ruoyi.db.domain.SpecialCostomManagerInfo;
import com.ruoyi.db.model.param.BatchEditChannelParam;
import com.ruoyi.db.model.param.ChannelInfoParam;
import com.ruoyi.extend.enums.ChannelTypeEnum;
import com.ruoyi.extend.service.IChannelInfoService;
import com.ruoyi.extend.service.ICountInfoService;
import com.ruoyi.extend.service.IPageTypeInfoService;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.market.constant.SystemConstant;
import com.ruoyi.market.enums.ManagerTypeEnum;
import com.ruoyi.market.service.IApplicationInfoService;
import com.ruoyi.product.service.IProductPushService;
import com.ruoyi.special.service.ISpecialCostomManagerInfoService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.wapper.ChannelInfoWapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 渠道信息Controller
 * 
 * @author ruoyi
 * @date 2022-08-04
 */
@Controller
@RequestMapping("/extend/channel")
public class ChannelInfoController extends BaseController
{
    private String prefix = "extend/channel";

    @Autowired
    private IChannelInfoService channelInfoService;
    @Autowired
    private IPageTypeInfoService pageTypeInfoService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IApplicationInfoService applicationInfoService;
    @Autowired
    private IProductPushService productPushService;
    @Autowired
    private ISpecialCostomManagerInfoService specialCostomManagerInfoService;

    @RequiresPermissions("extend:channel:view")
    @GetMapping()
    public String channel(ModelMap mmap)
    {

        ChannelInfoParam channelInfoParam = new ChannelInfoParam();
        List<Map<String, String>> channelInfoList = channelInfoService.selectSimpleMapInfo(channelInfoParam);
        mmap.put("channelInfoList", channelInfoList);

        List<Map<String, Object>> channelTypeList = ChannelTypeEnum.getShowMap();
        mmap.put("channelTypeList", channelTypeList);

        List<Map<String, Object>> appTypeList = applicationInfoService.getAppTypeList();
        mmap.put("appTypeList", appTypeList);

        List<Map<String, Object>> managerInfoList = specialCostomManagerInfoService.getManagerInfoList(ManagerTypeEnum.CHANNEL.getValue());
        mmap.put("managerInfoList", managerInfoList);

        return prefix + "/channel";
    }

    /**
     * 查询渠道信息列表
     */
    @RequiresPermissions("extend:channel:view")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ChannelInfoParam channelInfoParam)
    {

        startPage();
        List<Map<String, Object>> mapList = channelInfoService.selectChannelInfoListMap(channelInfoParam);
        mapList = new ChannelInfoWapper(mapList).wrap();
        return getDataTable(mapList);
    }

    /**
     * 我的渠道
     * @param mmap
     * @return
     */
    @RequiresPermissions("extend:channel:mine")
    @GetMapping("/mine")
    public String mine(ModelMap mmap)
    {
        SysUser sysUser = getSysUser();

        ChannelInfoParam channelInfoParam = new ChannelInfoParam();
        channelInfoParam.setOwnerId(String.valueOf(sysUser.getUserId()));
        List<Map<String, String>> channelInfoList = channelInfoService.selectSimpleMapInfo(channelInfoParam);
        mmap.put("channelInfoList", channelInfoList);

        List<Map<String, Object>> channelTypeList = ChannelTypeEnum.getShowMap();
        mmap.put("channelTypeList", channelTypeList);

        List<Map<String, Object>> appTypeList = applicationInfoService.getAppTypeList();
        mmap.put("appTypeList", appTypeList);

        return prefix + "/mine";
    }

    /**
     * 查询渠道信息列表
     */
    @RequiresPermissions("extend:channel:mine")
    @PostMapping("/mineList")
    @ResponseBody
    public TableDataInfo mineList(ChannelInfoParam channelInfoParam)
    {
        SysUser sysUser = getSysUser();
        channelInfoParam.setOwnerId(String.valueOf(sysUser.getUserId()));

        startPage();
        List<Map<String, Object>> mapList = channelInfoService.selectChannelInfoListMap(channelInfoParam);
        mapList = new ChannelInfoWapper(mapList).wrap();
        return getDataTable(mapList);
    }

    /**
     * 新增渠道信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {

        String channelCode = RandomUtil.randomStringUpper(6);
        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelCode(channelCode);
        if (ObjectUtils.isNotEmpty(channelInfo)){
            channelCode = RandomUtil.randomStringUpper(7);
            channelInfo = channelInfoService.selectChannelInfoByChannelCode(channelCode);
            if (ObjectUtils.isEmpty(channelInfo)){
                mmap.put("channelCode", channelCode);
            }
        }else{
            mmap.put("channelCode", channelCode);
        }

        //  落地页类型
        List<Map<String, Object>> pageTypeMapList = pageTypeInfoService.listMap();
        mmap.put("typeList", pageTypeMapList);

        // 产品信息
        List<Map<String, Object>> productMapList = productPushService.listOnLineMap(new ProductPush());
        mmap.put("productList", productMapList);

        // 来源信息
        List<Map<String, Object>> sourceMapList = SystemConstant.mapList;
        mmap.put("sourceList", sourceMapList);

        List<Map<String, Object>> channelTypeList = ChannelTypeEnum.getShowMap();
        mmap.put("channelTypeList", channelTypeList);

        /**
         * 应用列表
         */
        List<Map<String, Object>> appTypeList = applicationInfoService.getAppTypeList();
        mmap.put("appTypeList", appTypeList);

        return prefix + "/add";
    }

    /**
     * 新增保存渠道信息
     */
    @RequiresPermissions("extend:channel:add")
    @Log(title = "渠道信息-新增", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ChannelInfoParam channelInfoParam)
    {

        /**
         * 如果是注册计价的渠道，则生成用户的登陆信息
         */
        if (ObjectUtil.equal(channelInfoParam.getChargeType(), Integer.valueOf(2))){
            String numbers = RandomUtil.randomNumbers(11);
            // 注册用户信息
            SysUser sysUser = new SysUser();
            sysUser.setUserName(channelInfoParam.getChannelName());
            sysUser.setLoginName(numbers);

            String password = numbers.substring(5);
            sysUser.setPassword(password);
            sysUser.setSalt(ShiroUtils.randomSalt());
            sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt()));
            sysUser.setCreateBy(getLoginName());

            sysUser.setDeptId(213L);
            sysUser.setRoleIds(new Long[]{107L});
            int i = sysUserService.insertUser(sysUser);
            if (i<1){
                return toAjax(0);
            }
            channelInfoParam.setAdminUid(String.valueOf(sysUser.getUserId()));
            channelInfoParam.setAdminAccount(numbers);
            channelInfoParam.setAdminPasswd(password);
        }

        return toAjax(channelInfoService.insertChannelInfo(channelInfoParam));
    }

    /**
     * 修改渠道信息
     */
    @RequiresPermissions("extend:channel:edit")
    @GetMapping("/edit/{channelCode}")
    public String edit(@PathVariable("channelCode") String channelCode, ModelMap mmap)
    {
        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelCode(channelCode);
        mmap.put("channelInfo", channelInfo);
        //  落地页类型
        List<Map<String, Object>> pageTypeMapList = pageTypeInfoService.listMap();
        for (Map<String, Object> map: pageTypeMapList){
            String type = (String) map.get("type");
            if (StringUtils.equals(type, channelInfo.getPageType())){
                map.put("flag", true);
            }else{
                map.put("flag", false);
            }
        }
        mmap.put("typeList", pageTypeMapList);


        JSONArray jsonArray = JSON.parseArray(channelInfo.getNotIncludeProduct());
        // 产品信息
        List<Map<String, Object>> productMapList = productPushService.listOnLineMap(new ProductPush());
        for (Map<String, Object> map: productMapList){
            Integer value = (Integer) map.get("value");
            if (ObjectUtils.isNotEmpty(jsonArray) && jsonArray.contains(String.valueOf(value))){
                map.put("flag", true);
            }else{
                map.put("flag", false);
            }
        }
        mmap.put("productList", productMapList);

        JSONArray jsonArraySource = JSON.parseArray(channelInfo.getNotIncludeSource());
        // 来源信息
        List<Map<String, Object>> sourceMapList = SystemConstant.mapList;
        for (Map<String, Object> map: sourceMapList){
            String value = (String) map.get("value");
            if (ObjectUtils.isNotEmpty(jsonArraySource) && jsonArraySource.contains(value)){
                map.put("flag", true);
            }else{
                map.put("flag", false);
            }
        }
        mmap.put("sourceList", sourceMapList);

        List<Map<String, Object>> channelTypeList = ChannelTypeEnum.getShowMap();
        mmap.put("channelTypeList", channelTypeList);

        List<Map<String, Object>> appTypeList = applicationInfoService.getAppTypeList();
        mmap.put("appTypeList", appTypeList);

        return prefix + "/edit";
    }

    /**
     * 修改保存渠道信息
     */
    @RequiresPermissions("extend:channel:edit")
    @Log(title = "渠道信息-编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ChannelInfoParam channelInfoParam)
    {
        return toAjax(channelInfoService.updateChannelInfo(channelInfoParam));
    }

    /**
     * 删除渠道信息
     */
    @RequiresPermissions("extend:channel:remove")
    @Log(title = "渠道信息-删除", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(channelInfoService.deleteChannelInfoByIds(ids));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("extend:channel:edit")
    @Log(title = "渠道信息-修改状态", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(ChannelInfoParam channelInfoParam)
    {
        int result = channelInfoService.updateChannelInfo(channelInfoParam);
        return toAjax(result);
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("extend:channel:edit")
    @Log(title = "渠道信息-修改短信", businessType = BusinessType.UPDATE)
    @PostMapping("/changeSmsFlag")
    @ResponseBody
    public AjaxResult changeSmsFlag(ChannelInfoParam channelInfoParam)
    {
        int result = channelInfoService.updateChannelInfo(channelInfoParam);
        return toAjax(result);
    }

    /**
     * 新增渠道统计
     */
    @RequiresPermissions("extend:channel:batchEdit")
    @GetMapping("/batchEdit")
    public String batchEdit(ModelMap mmap)
    {
        //  落地页类型
        List<Map<String, Object>> pageTypeMapList = pageTypeInfoService.listMap();
        mmap.put("typeList", pageTypeMapList);

        List<Map<String, Object>> channelTypeList = ChannelTypeEnum.getShowMap();
        mmap.put("channelTypeList", channelTypeList);

        return prefix + "/batchEdit";
    }

    /**
     * 修改保存渠道统计
     */
    @RequiresPermissions("extend:channel:batchEdit")
    @Log(title = "渠道信息-批量修改", businessType = BusinessType.UPDATE)
    @PostMapping("/batchEditSave")
    @ResponseBody
    public AjaxResult batchEditSave(BatchEditChannelParam batchEditChannelParam)
    {
        return toAjax(channelInfoService.batchEditSave(batchEditChannelParam));
    }

    /**
     * 新增渠道统计
     */
    @RequiresPermissions("extend:channel:editMain")
    @GetMapping("/editMain/{channelCode}")
    public String editMain(ModelMap mmap, @PathVariable("channelCode") String channelCode)
    {
        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelCode(channelCode);
        mmap.put("channelInfo", channelInfo);

        List<Map<String, Object>> managerInfoList = specialCostomManagerInfoService.getManagerInfoList(ManagerTypeEnum.CHANNEL.getValue());
        mmap.put("managerInfoList", managerInfoList);

        return prefix + "/editMain";
    }

    @Autowired
    ICountInfoService countInfoService;

    @RequiresPermissions("extend:channel:editMain")
    @Log(title = "渠道信息-修改敏感", businessType = BusinessType.UPDATE)
    @PostMapping("/editMainSave")
    @ResponseBody
    public AjaxResult editMainSave(ChannelInfoParam channelInfoParam)
    {

        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelCode(channelInfoParam.getChannelCode());
        boolean editOwnerId = !StrUtil.equals(channelInfoParam.getOwnerId(), channelInfo.getOwnerId());

        SpecialCostomManagerInfo specialCostomManagerInfo = null;
        if (editOwnerId){
            specialCostomManagerInfo = specialCostomManagerInfoService.selectSpecialCostomManagerInfoByUserId(Long.valueOf(channelInfoParam.getOwnerId()));
            channelInfoParam.setOwnerName(specialCostomManagerInfo.getUsername());
        }

        int i = channelInfoService.updateChannelInfo(channelInfoParam);
        if (i > 0 && editOwnerId){
            // 更新统计信息数据
            CountInfo countInfo = new CountInfo();
            countInfo.setChannelCode(channelInfoParam.getChannelCode());
            countInfo.setOwnerId(String.valueOf(specialCostomManagerInfo.getUserId()));
            countInfo.setOwnerName(specialCostomManagerInfo.getUsername());
            countInfoService.updateCountInfo(countInfo);
        }

        return toAjax(i);
    }

    /**
     * 修改保存渠道统计
     */
    @PostMapping("/checkName")
    @ResponseBody
    public AjaxResult checkName(@RequestParam("channelName") String channelName)
    {
        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelName(channelName);

        if (ObjectUtil.isNotEmpty(channelInfo)){
            return AjaxResult.error();
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelName", channelName);

        return AjaxResult.success(jsonObject);
    }

}
